package com.tanhua.dubbo.api;


import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLikeApiImpl implements UserLikeApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public boolean likeuser(Long userId, Long likeuserId, boolean isLike) {
        try {
            //先查询userlike集合是否已经有了不喜欢的表示，如果有更新成喜欢，如果没有就添加新的数据
            Query query = Query.query(Criteria.where("userId").is(userId)
            .and("likeUserId").is(likeuserId));
            UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
            //如果没有数据，则封装数据保存到userlike表
            if (userLike == null) {
                //保存喜欢数据到userlike
                UserLike userLike1 = new UserLike();
                userLike1.setUserId(userId);
                userLike1.setLikeUserId(likeuserId);
                userLike1.setIsLike(isLike);
                userLike1.setCreated(System.currentTimeMillis());
                userLike1.setUpdated(System.currentTimeMillis());
                mongoTemplate.save(userLike1);
            }else {
                //如果已存在则更新
                Update update = Update.update("isLike",isLike).set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<UserLike> loveCount(Long userId) {
        //从userlike表里面取出我喜欢的人
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("isLike").is(true));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        return userLikes;
    }

    @Override
    public List<UserLike> fanCount(Long likeUserId) {
        //从userlike表里面取出喜欢我的人
        Query query = Query.query(Criteria.where("likeUserId").is(likeUserId)
                .and("isLike").is(true));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        return userLikes;
    }

    @Override
    public void cancelLikes(Long userId, Long likeUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        mongoTemplate.remove(query, UserLike.class);
    }

}
